package logger

import (
	"fmt"
	"giot/pkg/util"
	"os"
	"strings"
	"time"
)

type AutoDeleteLog struct {
	running bool
}

func (ad *AutoDeleteLog) Start(basePath string, before int) {
	prefix := []string{"DEBUG_", "INFO_", "WARRING_", "ERROR_", "OTHER_"}
	ad.deleteLogFile(prefix, basePath, before)
	go ad.StartAutoDelete(prefix, basePath, before)
}

func (ad *AutoDeleteLog) StartAutoDelete(filePrefix []string, basePath string, before int) {
	ticker := time.NewTicker(time.Hour)
	defer ticker.Stop()
	ad.running = true
	for ad.running {
		select {
		case <-ticker.C:
			ad.deleteLogFile(filePrefix, basePath, before)
		}
	}
}

func (ad *AutoDeleteLog) Stop() {
	ad.running = false
}

func (ad *AutoDeleteLog) deleteLogFile(filePrefix []string, basePath string, before int) {
	d := time.Now().Add(-time.Duration(before) * time.Hour)
	for x := range filePrefix {
		overdue := ad.findOverdue(filePrefix[x], basePath, d)
		if overdue != nil {
			for i := range overdue {
				err := os.Remove(overdue[i])
				if err != nil {
					GetLog().Errorf("删除文件[%v]失败,错误信息:%v", overdue[i], err)
				}
			}
		}
	}
}

func (ad *AutoDeleteLog) findOverdue(h, basePath string, before time.Time) []string {
	exists := util.PathExists(basePath)
	if !exists {
		return nil
	}
	files, err := os.ReadDir(basePath)
	if err != nil {
		GetLog().Errorf("读目录[%v]发生错误,错误信息:%v", basePath, err)
		return nil
	}
	var result []string
	for i := range files {
		name := strings.ToUpper(files[i].Name())
		if strings.Index(name, h) == 0 {
			s1 := name[strings.Index(name, h)+len(h):]
			if strings.LastIndex(s1, ".LOG") > 0 {
				s1 = s1[:len(s1)-4]
				modTime, err := time.Parse("2006-01-02_15", s1)
				if err == nil && modTime.Sub(before).Hours() <= 0 {
					result = append(result, fmt.Sprintf("%v%v%v", basePath, util.Separator(), files[i].Name()))
				}
			}
		}
	}
	return result
}
